package com.thoughtful.remoting.transport.netty.server;

import java.net.InetAddress;
import java.util.concurrent.TimeUnit;

import com.thoughtful.config.RpcServiceConfig;
import com.thoughtful.provider.ServiceProvider;
import com.thoughtful.provider.impl.ZkServiceProviderImpl;
import com.thoughtful.remoting.transport.netty.codec.RpcMessageDecoder;
import com.thoughtful.remoting.transport.netty.codec.RpcMessageEncoder;
import com.thougtful.factory.SingletonFactory;
import com.thougtful.utils.RuntimeUtil;
import com.thougtful.utils.concurrent.threadpool.ThreadPoolFactoryUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author Thoughtful
 * @createTime 2022/10/17 - 23:44
 **/
@Slf4j
@Component
public class NettyRpcServer {

    public static final int PORT = 9999;

    private final ServiceProvider serviceProvider = SingletonFactory.getSingleton(ZkServiceProviderImpl.class);

    public void registerService(RpcServiceConfig rpcServiceConfig) {
        serviceProvider.publishService(rpcServiceConfig);
    }

    @SneakyThrows
    public void start() {
        String host = InetAddress.getLocalHost().getHostAddress();
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        DefaultEventExecutorGroup serverHandlerGroup = new DefaultEventExecutorGroup(RuntimeUtil.cpus() * 2,
            ThreadPoolFactoryUtil.createThreadFactory("service-handler-group", false));

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                // TCP 默认开启了 Nagle 算法, 该算法的作用是尽可能的发送大数据块, 以减少网络传输
                // TPC_NODELAY 参数的作用就是控制是否启用 Nagle 算法
                .childOption(ChannelOption.TCP_NODELAY, true)
                // 是否开启 TCP 底层的心跳机制
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                // 表示系统用于临时存放已完成三次握手的请求的队列的最大长度, 如果连接建立频繁, 服务器处理创建新连接较慢, 可以适当调大
                .option(ChannelOption.SO_BACKLOG, 128)
                .handler(new LoggingHandler(LogLevel.INFO))
                // 当客户端第一次发起请求的时候才会进行初始化
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        // 30 秒之类没有收到客户端请求, 则关闭连接
                        pipeline.addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS));
                        pipeline.addLast(new RpcMessageEncoder());
                        pipeline.addLast(new RpcMessageDecoder());
                        pipeline.addLast(serverHandlerGroup, new NettyRpcServerHandler());
                    }
                });

            // 绑定端口, 同步等待绑定成功
            ChannelFuture f = serverBootstrap.bind(host, PORT).sync();
            // 等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("occur exception when start netty server: ", e);
        } finally {
            log.info("shutdown bossGroup and workerGroup");
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            serverHandlerGroup.shutdownGracefully();
        }
    }

}
